
import requestConfig from './request-config.js'
import requestEnv from './request-env.js'

const service = uni.$u.http
let lockLogin = false
module.exports = (vm) => {
  // 初始化请求配置
  service.setConfig((config) => {
    config.timeout = 20000
    requestEnv.setEnvConfig(config)
    return config
  })
  /**  请求拦截 */
  service.interceptors.request.use((
    config) => {
    if (config?.custom?.showLoading) uni.showLoading({ title: '加载中', mask: false })
    requestConfig.setRequestConfig(config, vm)
    return config
  },
  config => {
    return Promise.reject(config)
  })
  /** 响应拦截 */
  service.interceptors.response.use((response) => {
    uni.hideLoading()
    if (typeof response.data === 'string') response.data = JSON.parse(response.data)
    const res = response.data
    if (response.statusCode !== 200 || Number(res.code) !== 0) {
      // 处理异常
      if (Number(res.code) === 1000 || Number(res.code) === 1001) {
        if (!lockLogin) {
          lockLogin = true
          console.error(response.config.url, res.msg)
          return
        }
      }
      // 默认对报错进行提示
      if (response?.config?.custom?.showErrorToast) setTimeout(() => { uni.$u.toast(res.msg) }, 200)
      return Promise.reject(res)
    } else {
      if (lockLogin) {
        lockLogin = false
      }
      return response.data
    }
  },
  responseError => {
    uni.hideLoading()
    return Promise.reject(responseError)
  })
}
